<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>新闻表结构编辑 - 后台管理系统</title>
    <style>
        body {
            font-family: 'Microsoft YaHei', Arial, sans-serif;
            margin: 0;
            padding: 0;
            background-color: #f5f5f5;
            color: #333;
        }
        .navbar {
            background-color: #2c3e50;
            color: white;
            padding: 15px 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .navbar h1 {
            margin: 0;
            font-size: 24px;
        }
        .navbar a {
            color: white;
            text-decoration: none;
            margin-left: 15px;
        }
        .container {
            max-width: 1200px;
            margin: 20px auto;
            padding: 20px;
            background-color: white;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        .page-header {
            margin-bottom: 20px;
            padding-bottom: 10px;
            border-bottom: 1px solid #eee;
        }
        .page-header h2 {
            margin: 0;
            font-size: 22px;
            color: #2c3e50;
        }
        .section {
            margin-bottom: 30px;
        }
        .section-title {
            font-size: 18px;
            margin-bottom: 15px;
            color: #34495e;
        }
        .field-list {
            width: 100%;
            border-collapse: collapse;
            margin-bottom: 20px;
        }
        .field-list th,
        .field-list td {
            padding: 12px 15px;
            border: 1px solid #ddd;
            text-align: left;
        }
        .field-list th {
            background-color: #f8f9fa;
            font-weight: bold;
            color: #2c3e50;
        }
        .field-list tr:nth-child(even) {
            background-color: #f9f9f9;
        }
        .field-list tr:hover {
            background-color: #f1f1f1;
        }
        .btn {
            display: inline-block;
            padding: 8px 16px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            text-decoration: none;
            font-size: 14px;
            transition: background-color 0.3s;
        }
        .btn-primary {
            background-color: #3498db;
            color: white;
        }
        .btn-primary:hover {
            background-color: #2980b9;
        }
        .btn-success {
            background-color: #2ecc71;
            color: white;
        }
        .btn-success:hover {
            background-color: #27ae60;
        }
        .btn-danger {
            background-color: #e74c3c;
            color: white;
        }
        .btn-danger:hover {
            background-color: #c0392b;
        }
        .btn-info {
            background-color: #1abc9c;
            color: white;
        }
        .btn-info:hover {
            background-color: #16a085;
        }
        .btn-secondary {
            background-color: #95a5a6;
            color: white;
        }
        .btn-secondary:hover {
            background-color: #7f8c8d;
        }
        .form-group {
            margin-bottom: 15px;
        }
        .form-group label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
            color: #34495e;
        }
        .form-group input,
        .form-group select,
        .form-group textarea {
            width: 100%;
            padding: 8px 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 14px;
        }
        .form-group input:focus,
        .form-group select:focus,
        .form-group textarea:focus {
            outline: none;
            border-color: #3498db;
            box-shadow: 0 0 5px rgba(52, 152, 219, 0.3);
        }
        .message {
            padding: 12px 15px;
            border-radius: 4px;
            margin-bottom: 15px;
            display: none;
        }
        .message.success {
            background-color: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        .message.error {
            background-color: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }
        .message.info {
            background-color: #d1ecf1;
            color: #0c5460;
            border: 1px solid #bee5eb;
        }
        .button-group {
            margin-top: 20px;
        }
        .button-group .btn {
            margin-right: 10px;
        }
        .note {
            background-color: #f8f9fa;
            padding: 15px;
            border-left: 4px solid #3498db;
            margin-bottom: 20px;
            font-size: 14px;
        }
        .field-type-options {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
            gap: 10px;
            margin-bottom: 15px;
        }
        .field-type-options label {
            display: flex;
            align-items: center;
            padding: 8px 12px;
            border: 1px solid #ddd;
            border-radius: 4px;
            cursor: pointer;
            transition: all 0.3s;
        }
        .field-type-options label:hover {
            background-color: #f8f9fa;
            border-color: #3498db;
        }
        .field-type-options input[type="radio"] {
            margin-right: 8px;
            width: auto;
        }
        .add-field-section {
            background-color: #f8f9fa;
            padding: 20px;
            border-radius: 8px;
            margin-bottom: 20px;
        }
        .hidden {
            display: none;
        }
        .validation-message {
            color: #e74c3c;
            font-size: 12px;
            margin-top: 5px;
        }
    </style>
</head>
<body>
    <div class="navbar">
        <h1>后台管理系统</h1>
        <div>
            <a href="/admin">首页</a>
            <a href="/admin/news/structure">表结构编辑</a>
            <a href="/logout">退出登录</a>
        </div>
    </div>

    <div class="container">
        <div class="page-header">
            <h2>新闻表结构编辑</h2>
        </div>

        <div class="message" id="message"></div>

        <div class="note">
            <strong>注意事项：</strong><br>
            1. 修改表结构前请确保已备份数据库<br>
            2. 添加或修改字段可能会影响现有数据<br>
            3. 删除字段将导致该字段的所有数据丢失<br>
            4. 主键字段（id）不能被删除或修改
        </div>

        <div class="section">
            <h3 class="section-title">当前表结构</h3>
            <div id="current-structure">
                <table class="field-list">
                    <thead>
                        <tr>
                            <th>字段名</th>
                            <th>数据类型</th>
                            <th>长度</th>
                            <th>是否可为空</th>
                            <th>默认值</th>
                            <th>索引</th>
                            <th>描述</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody id="fields-table-body">
                        <!-- 字段列表将通过JavaScript动态生成 -->
                    </tbody>
                </table>
            </div>
        </div>

        <div class="add-field-section">
            <h3 class="section-title">添加新字段</h3>
            <form id="add-field-form">
                <div class="form-group">
                    <label for="new-field-name">字段名：</label>
                    <input type="text" id="new-field-name" name="field_name" placeholder="请输入字段名（英文、数字、下划线）" required>
                    <div class="validation-message" id="field-name-validation"></div>
                </div>

                <div class="form-group">
                    <label>数据类型：</label>
                    <div class="field-type-options">
                        <label><input type="radio" name="field_type" value="VARCHAR" checked> VARCHAR</label>
                        <label><input type="radio" name="field_type" value="TEXT"> TEXT</label>
                        <label><input type="radio" name="field_type" value="INT"> INT</label>
                        <label><input type="radio" name="field_type" value="BIGINT"> BIGINT</label>
                        <label><input type="radio" name="field_type" value="FLOAT"> FLOAT</label>
                        <label><input type="radio" name="field_type" value="DOUBLE"> DOUBLE</label>
                        <label><input type="radio" name="field_type" value="DATE"> DATE</label>
                        <label><input type="radio" name="field_type" value="DATETIME"> DATETIME</label>
                        <label><input type="radio" name="field_type" value="BOOLEAN"> BOOLEAN</label>
                        <label><input type="radio" name="field_type" value="JSON"> JSON</label>
                    </div>
                </div>

                <div class="form-group">
                    <label for="new-field-length">长度（仅VARCHAR类型需要）：</label>
                    <input type="number" id="new-field-length" name="field_length" placeholder="如255" min="1" max="65535">
                </div>

                <div class="form-group">
                    <label for="new-field-nullable">是否可为空：</label>
                    <select id="new-field-nullable" name="field_nullable">
                        <option value="1">是</option>
                        <option value="0">否</option>
                    </select>
                </div>

                <div class="form-group">
                    <label for="new-field-default">默认值：</label>
                    <input type="text" id="new-field-default" name="field_default" placeholder="如'默认值'或NULL">
                </div>

                <div class="form-group">
                    <label for="new-field-index">索引：</label>
                    <select id="new-field-index" name="field_index">
                        <option value="">无</option>
                        <option value="INDEX">普通索引</option>
                        <option value="UNIQUE">唯一索引</option>
                    </select>
                </div>

                <div class="form-group">
                    <label for="new-field-comment">描述：</label>
                    <textarea id="new-field-comment" name="field_comment" rows="2" placeholder="请输入字段描述"></textarea>
                </div>

                <button type="button" class="btn btn-primary" id="add-field-btn">添加字段</button>
            </form>
        </div>

        <div class="button-group">
            <button class="btn btn-success" id="save-changes-btn">保存表结构更改</button>
            <a href="/admin" class="btn btn-secondary">返回首页</a>
        </div>
    </div>

    <!-- 编辑字段弹窗 -->
    <div id="edit-field-modal" style="position: fixed; top: 0; left: 0; width: 100%; height: 100%; background-color: rgba(0,0,0,0.5); display: none; justify-content: center; align-items: center; z-index: 1000;">
        <div style="background-color: white; padding: 30px; border-radius: 8px; width: 90%; max-width: 600px;">
            <h3>编辑字段</h3>
            <form id="edit-field-form">
                <input type="hidden" id="edit-field-original-name" name="original_name">
                
                <div class="form-group">
                    <label for="edit-field-name">字段名：</label>
                    <input type="text" id="edit-field-name" name="field_name" required>
                </div>

                <div class="form-group">
                    <label>数据类型：</label>
                    <div class="field-type-options">
                        <label><input type="radio" name="edit_field_type" value="VARCHAR"> VARCHAR</label>
                        <label><input type="radio" name="edit_field_type" value="TEXT"> TEXT</label>
                        <label><input type="radio" name="edit_field_type" value="INT"> INT</label>
                        <label><input type="radio" name="edit_field_type" value="BIGINT"> BIGINT</label>
                        <label><input type="radio" name="edit_field_type" value="FLOAT"> FLOAT</label>
                        <label><input type="radio" name="edit_field_type" value="DOUBLE"> DOUBLE</label>
                        <label><input type="radio" name="edit_field_type" value="DATE"> DATE</label>
                        <label><input type="radio" name="edit_field_type" value="DATETIME"> DATETIME</label>
                        <label><input type="radio" name="edit_field_type" value="BOOLEAN"> BOOLEAN</label>
                        <label><input type="radio" name="edit_field_type" value="JSON"> JSON</label>
                    </div>
                </div>

                <div class="form-group">
                    <label for="edit-field-length">长度（仅VARCHAR类型需要）：</label>
                    <input type="number" id="edit-field-length" name="field_length" min="1" max="65535">
                </div>

                <div class="form-group">
                    <label for="edit-field-nullable">是否可为空：</label>
                    <select id="edit-field-nullable" name="field_nullable">
                        <option value="1">是</option>
                        <option value="0">否</option>
                    </select>
                </div>

                <div class="form-group">
                    <label for="edit-field-default">默认值：</label>
                    <input type="text" id="edit-field-default" name="field_default">
                </div>

                <div class="form-group">
                    <label for="edit-field-index">索引：</label>
                    <select id="edit-field-index" name="field_index">
                        <option value="">无</option>
                        <option value="INDEX">普通索引</option>
                        <option value="UNIQUE">唯一索引</option>
                    </select>
                </div>

                <div class="form-group">
                    <label for="edit-field-comment">描述：</label>
                    <textarea id="edit-field-comment" name="field_comment" rows="2"></textarea>
                </div>

                <div class="button-group">
                    <button type="submit" class="btn btn-primary">保存修改</button>
                    <button type="button" class="btn btn-secondary" id="close-edit-modal">取消</button>
                </div>
            </form>
        </div>
    </div>

    <script>
        // 存储当前表结构数据
        let tableFields = [];
        let modifiedFields = [];
        let addedFields = [];
        let deletedFields = [];

        // 显示消息函数
        function showMessage(type, message) {
            const messageElement = document.getElementById('message');
            messageElement.className = `message ${type}`;
            messageElement.textContent = message;
            messageElement.style.display = 'block';
            
            setTimeout(() => {
                messageElement.style.display = 'none';
            }, 5000);
        }

        // 初始化页面
        function initPage() {
            // 获取表结构数据
            fetch('/admin/news/structure/data')
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        tableFields = data.fields;
                        renderFieldsTable();
                    } else {
                        showMessage('error', '获取表结构失败：' + data.message);
                    }
                })
                .catch(error => {
                    showMessage('error', '获取表结构时发生错误：' + error.message);
                    console.error('Error fetching table structure:', error);
                });

            // 绑定添加字段按钮事件
            document.getElementById('add-field-btn').addEventListener('click', addNewField);

            // 绑定保存更改按钮事件
            document.getElementById('save-changes-btn').addEventListener('click', saveTableStructure);

            // 绑定关闭编辑弹窗事件
            document.getElementById('close-edit-modal').addEventListener('click', () => {
                document.getElementById('edit-field-modal').style.display = 'none';
            });

            // 绑定编辑字段表单提交事件
            document.getElementById('edit-field-form').addEventListener('submit', (e) => {
                e.preventDefault();
                saveFieldEdit();
            });

            // 字段名输入验证
            const fieldNameInput = document.getElementById('new-field-name');
            const fieldNameValidation = document.getElementById('field-name-validation');
            
            fieldNameInput.addEventListener('input', () => {
                const fieldName = fieldNameInput.value;
                if (fieldName && !/^[a-zA-Z0-9_]+$/.test(fieldName)) {
                    fieldNameValidation.textContent = '字段名只能包含字母、数字和下划线';
                } else if (fieldName && fieldName === 'id') {
                    fieldNameValidation.textContent = 'id是系统保留字段，不能使用';
                } else {
                    fieldNameValidation.textContent = '';
                }
            });

            // 数据类型选择事件
            const fieldTypeRadios = document.querySelectorAll('input[name="field_type"]');
            const fieldLengthInput = document.getElementById('new-field-length');
            
            fieldTypeRadios.forEach(radio => {
                radio.addEventListener('change', () => {
                    if (radio.value === 'VARCHAR') {
                        fieldLengthInput.disabled = false;
                        fieldLengthInput.required = true;
                    } else {
                        fieldLengthInput.disabled = true;
                        fieldLengthInput.required = false;
                    }
                });
            });
        }

        // 渲染字段表格
        function renderFieldsTable() {
            const tableBody = document.getElementById('fields-table-body');
            tableBody.innerHTML = '';

            tableFields.forEach(field => {
                const row = document.createElement('tr');
                
                // 检查字段是否被修改过
                const modifiedField = modifiedFields.find(f => f.name === field.name);
                const isModified = !!modifiedField;
                const displayField = isModified ? modifiedField : field;
                
                // 检查字段是否被标记为删除
                const isDeleted = deletedFields.includes(field.name);
                
                if (isDeleted) {
                    row.style.textDecoration = 'line-through';
                    row.style.color = '#999';
                }
                
                row.innerHTML = `
                    <td>${displayField.name}</td>
                    <td>${displayField.type}</td>
                    <td>${displayField.length || '-'}</td>
                    <td>${displayField.nullable ? '是' : '否'}</td>
                    <td>${displayField.default_value || '-'}</td>
                    <td>${displayField.index || '-'}</td>
                    <td>${displayField.comment || '-'}</td>
                    <td>
                        ${field.name === 'id' ? 
                            '<span class="btn btn-secondary" disabled>主键</span>' : 
                            `
                                <button class="btn btn-info edit-field-btn" data-field="${field.name}">编辑</button>
                                ${isDeleted ? 
                                    '<button class="btn btn-success restore-field-btn" data-field="' + field.name + '">恢复</button>' : 
                                    '<button class="btn btn-danger delete-field-btn" data-field="' + field.name + '">删除</button>'
                                }
                            `
                        }
                    </td>
                `;
                
                tableBody.appendChild(row);
            });

            // 绑定编辑和删除按钮事件
            document.querySelectorAll('.edit-field-btn').forEach(btn => {
                btn.addEventListener('click', () => {
                    const fieldName = btn.getAttribute('data-field');
                    openEditFieldModal(fieldName);
                });
            });

            document.querySelectorAll('.delete-field-btn').forEach(btn => {
                btn.addEventListener('click', () => {
                    const fieldName = btn.getAttribute('data-field');
                    if (confirm(`确定要删除字段 "${fieldName}" 吗？这将导致该字段的所有数据丢失！`)) {
                        deleteField(fieldName);
                    }
                });
            });

            document.querySelectorAll('.restore-field-btn').forEach(btn => {
                btn.addEventListener('click', () => {
                    const fieldName = btn.getAttribute('data-field');
                    restoreField(fieldName);
                });
            });

            // 渲染添加的字段
            if (addedFields.length > 0) {
                addedFields.forEach(field => {
                    const row = document.createElement('tr');
                    row.style.backgroundColor = '#e8f8f5';
                    
                    row.innerHTML = `
                        <td>${field.name}</td>
                        <td>${field.type}</td>
                        <td>${field.length || '-'}</td>
                        <td>${field.nullable ? '是' : '否'}</td>
                        <td>${field.default_value || '-'}</td>
                        <td>${field.index || '-'}</td>
                        <td>${field.comment || '-'}</td>
                        <td>
                            <button class="btn btn-danger cancel-add-btn" data-field="${field.name}">取消添加</button>
                        </td>
                    `;
                    
                    tableBody.appendChild(row);
                });
            }

            // 绑定取消添加按钮事件
            document.querySelectorAll('.cancel-add-btn').forEach(btn => {
                btn.addEventListener('click', () => {
                    const fieldName = btn.getAttribute('data-field');
                    cancelAddField(fieldName);
                });
            });
        }

        // 添加新字段
        function addNewField() {
            const fieldNameInput = document.getElementById('new-field-name');
            const fieldName = fieldNameInput.value.trim();
            const fieldNameValidation = document.getElementById('field-name-validation');
            
            if (!fieldName) {
                fieldNameValidation.textContent = '请输入字段名';
                return;
            }
            
            if (!/^[a-zA-Z0-9_]+$/.test(fieldName)) {
                fieldNameValidation.textContent = '字段名只能包含字母、数字和下划线';
                return;
            }
            
            if (fieldName === 'id') {
                fieldNameValidation.textContent = 'id是系统保留字段，不能使用';
                return;
            }
            
            // 检查字段名是否已存在
            if (tableFields.some(f => f.name === fieldName) || addedFields.some(f => f.name === fieldName)) {
                fieldNameValidation.textContent = '该字段名已存在';
                return;
            }

            const fieldType = document.querySelector('input[name="field_type"]:checked').value;
            const fieldLength = fieldType === 'VARCHAR' ? document.getElementById('new-field-length').value : null;
            const fieldNullable = document.getElementById('new-field-nullable').value === '1';
            const fieldDefault = document.getElementById('new-field-default').value || null;
            const fieldIndex = document.getElementById('new-field-index').value || null;
            const fieldComment = document.getElementById('new-field-comment').value || null;

            // 验证VARCHAR类型的长度
            if (fieldType === 'VARCHAR' && (!fieldLength || isNaN(fieldLength) || fieldLength <= 0 || fieldLength > 65535)) {
                showMessage('error', 'VARCHAR类型的长度必须是1-65535之间的数字');
                return;
            }

            const newField = {
                name: fieldName,
                type: fieldType,
                length: fieldLength,
                nullable: fieldNullable,
                default_value: fieldDefault,
                index: fieldIndex,
                comment: fieldComment
            };

            addedFields.push(newField);
            renderFieldsTable();
            
            // 重置表单
            document.getElementById('add-field-form').reset();
            fieldNameValidation.textContent = '';
            
            showMessage('success', `成功添加字段 "${fieldName}"`);
        }

        // 打开编辑字段弹窗
        function openEditFieldModal(fieldName) {
            // 查找要编辑的字段
            const originalField = tableFields.find(f => f.name === fieldName);
            const modifiedField = modifiedFields.find(f => f.name === fieldName);
            const field = modifiedField || originalField;

            if (!field) {
                showMessage('error', '找不到要编辑的字段');
                return;
            }

            // 填充表单
            document.getElementById('edit-field-original-name').value = originalField.name;
            document.getElementById('edit-field-name').value = field.name;
            
            // 设置数据类型
            document.querySelectorAll('input[name="edit_field_type"]').forEach(radio => {
                radio.checked = radio.value === field.type;
            });
            
            // 设置长度
            const editFieldLength = document.getElementById('edit-field-length');
            editFieldLength.value = field.length || '';
            editFieldLength.disabled = field.type !== 'VARCHAR';
            
            // 设置可为空
            document.getElementById('edit-field-nullable').value = field.nullable ? '1' : '0';
            
            // 设置默认值
            document.getElementById('edit-field-default').value = field.default_value || '';
            
            // 设置索引
            document.getElementById('edit-field-index').value = field.index || '';
            
            // 设置描述
            document.getElementById('edit-field-comment').value = field.comment || '';

            // 显示弹窗
            document.getElementById('edit-field-modal').style.display = 'flex';
        }

        // 保存字段编辑
        function saveFieldEdit() {
            const originalName = document.getElementById('edit-field-original-name').value;
            const fieldName = document.getElementById('edit-field-name').value.trim();
            
            if (!fieldName) {
                showMessage('error', '请输入字段名');
                return;
            }
            
            if (!/^[a-zA-Z0-9_]+$/.test(fieldName)) {
                showMessage('error', '字段名只能包含字母、数字和下划线');
                return;
            }

            // 检查字段名是否与其他字段重复
            const nameExists = tableFields.some(f => f.name !== originalName && f.name === fieldName) || 
                              addedFields.some(f => f.name === fieldName);
            
            if (nameExists) {
                showMessage('error', '该字段名已存在');
                return;
            }

            const fieldType = document.querySelector('input[name="edit_field_type"]:checked').value;
            const fieldLength = fieldType === 'VARCHAR' ? document.getElementById('edit-field-length').value : null;
            const fieldNullable = document.getElementById('edit-field-nullable').value === '1';
            const fieldDefault = document.getElementById('edit-field-default').value || null;
            const fieldIndex = document.getElementById('edit-field-index').value || null;
            const fieldComment = document.getElementById('edit-field-comment').value || null;

            // 验证VARCHAR类型的长度
            if (fieldType === 'VARCHAR' && (!fieldLength || isNaN(fieldLength) || fieldLength <= 0 || fieldLength > 65535)) {
                showMessage('error', 'VARCHAR类型的长度必须是1-65535之间的数字');
                return;
            }

            const editedField = {
                name: fieldName,
                type: fieldType,
                length: fieldLength,
                nullable: fieldNullable,
                default_value: fieldDefault,
                index: fieldIndex,
                comment: fieldComment
            };

            // 检查字段是否被修改
            const originalField = tableFields.find(f => f.name === originalName);
            let isModified = false;
            
            for (const key in editedField) {
                if (key === 'name' && editedField[key] !== originalField[key]) {
                    isModified = true;
                    break;
                }
                if (key !== 'name' && editedField[key] !== originalField[key]) {
                    isModified = true;
                    break;
                }
            }

            if (isModified) {
                // 检查是否已经存在于modifiedFields中
                const existingIndex = modifiedFields.findIndex(f => f.name === originalName || f.name === fieldName);
                
                if (existingIndex >= 0) {
                    modifiedFields[existingIndex] = editedField;
                } else {
                    modifiedFields.push(editedField);
                }
            } else {
                // 移除未修改的字段
                const index = modifiedFields.findIndex(f => f.name === originalName);
                if (index >= 0) {
                    modifiedFields.splice(index, 1);
                }
            }

            // 关闭弹窗
            document.getElementById('edit-field-modal').style.display = 'none';
            
            // 重新渲染表格
            renderFieldsTable();
            
            showMessage('success', `成功保存字段 "${fieldName}" 的修改`);
        }

        // 删除字段
        function deleteField(fieldName) {
            // 检查字段是否已经在deletedFields中
            if (!deletedFields.includes(fieldName)) {
                deletedFields.push(fieldName);
            }
            
            // 如果字段在modifiedFields中，移除它
            const modifiedIndex = modifiedFields.findIndex(f => f.name === fieldName);
            if (modifiedIndex >= 0) {
                modifiedFields.splice(modifiedIndex, 1);
            }
            
            renderFieldsTable();
            showMessage('info', `已标记字段 "${fieldName}" 为删除`);
        }

        // 恢复字段
        function restoreField(fieldName) {
            // 从deletedFields中移除
            const index = deletedFields.indexOf(fieldName);
            if (index >= 0) {
                deletedFields.splice(index, 1);
            }
            
            renderFieldsTable();
            showMessage('success', `已恢复字段 "${fieldName}"`);
        }

        // 取消添加字段
        function cancelAddField(fieldName) {
            // 从addedFields中移除
            const index = addedFields.findIndex(f => f.name === fieldName);
            if (index >= 0) {
                addedFields.splice(index, 1);
            }
            
            renderFieldsTable();
            showMessage('info', `已取消添加字段 "${fieldName}"`);
        }

        // 保存表结构更改
        function saveTableStructure() {
            // 检查是否有更改
            if (modifiedFields.length === 0 && addedFields.length === 0 && deletedFields.length === 0) {
                showMessage('info', '没有检测到任何更改');
                return;
            }

            if (!confirm('确定要保存表结构更改吗？这可能会影响现有数据，建议先备份数据库！')) {
                return;
            }

            const changes = {
                modified: modifiedFields,
                added: addedFields,
                deleted: deletedFields
            };

            fetch('/admin/news/structure/edit', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(changes)
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    // 重置更改记录
                    modifiedFields = [];
                    addedFields = [];
                    deletedFields = [];
                    
                    // 重新加载表结构
                    fetch('/admin/news/structure/data')
                        .then(response => response.json())
                        .then(data => {
                            if (data.success) {
                                tableFields = data.fields;
                                renderFieldsTable();
                                showMessage('success', '表结构更改已成功保存！');
                            }
                        });
                } else {
                    showMessage('error', '保存表结构更改失败：' + data.message);
                }
            })
            .catch(error => {
                showMessage('error', '保存表结构更改时发生错误：' + error.message);
                console.error('Error saving table structure:', error);
            });
        }

        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', initPage);
    </script>
</body>
</html>